package com.cc.seckill.serviceImpl;

import com.cc.seckill.dao.SecKillDao;
import com.cc.seckill.dao.SuccessKilledDao;
import com.cc.seckill.dto.Exposer;
import com.cc.seckill.dto.SecKillExecution;
import com.cc.seckill.entity.SecKill;
import com.cc.seckill.entity.SuccessKill;
import com.cc.seckill.enums.SecKillStateEnum;
import com.cc.seckill.exception.RepeatKillException;
import com.cc.seckill.exception.SecKillCloseException;
import com.cc.seckill.exception.SecKillException;
import com.cc.seckill.service.SecKillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
@Service
public class SecKillServiceImpl implements SecKillService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SecKillDao secKillDao;

    @Autowired
    private SuccessKilledDao successKilledDao;

//    md5盐值字符串，用于混淆MD5
    private final String slat = "fjkankcvsal*)&30&*()ubfal2jfoiau2";

    @Override
    public List<SecKill> getSecKillList() {
        return secKillDao.queryAll(0,4);
    }

    @Override
    public SecKill getById(long secKillId) {
        return secKillDao.queryById(secKillId);
    }

    @Override
    public Exposer exportSecKillUrl(long secKillId) {
        SecKill secKill = secKillDao.queryById(secKillId);
        if (secKill == null)
        {
            return new Exposer(false,secKillId);
        }
        Date startTime = secKill.getStartTime();
        Date endTime = secKill.getEndTime();
//        系统当前的时间
        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()){
            return new Exposer(false,secKillId,nowTime.getTime(),startTime.getTime(),endTime.getTime());
        }

//      转化特定字符串的过程，不可逆
        String md5 = getMD5(secKillId);
        return new Exposer(true,md5,secKillId);
    }

    private String getMD5(long secKillId){
        String base = secKillId + "/" +slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }

    @Override
    @Transactional
    /**
     * 使用注解控制事务方法的优点：
     * 1、开发团队达成一致的约定，明确标注事务方法的风格。
     * 2、保证事务方法的执行时间尽可能短，不要穿插其他的网络操作，RPC/HTTP请求或者玻璃到事务方法的外部。
     * 3、不是所有的方法都需要事务。如只有一条修改操作，只读操作不需要事务控制。
     */
    public SecKillExecution executeSecKill(long secKillId, long userPhone, String md5) throws  RepeatKillException, SecKillException {
        if (md5 == null || !md5.equals(getMD5(secKillId))){
            throw new SecKillException("seckill data reworite");
        }
        Date nowTime = new Date();
        try {
            //        执行秒杀逻辑：减库存和记录购买记录
//         减库存
            int updateCount = secKillDao.reduceNumber(secKillId,nowTime);
            if (updateCount <=0 ){
//            没有更新记录，秒杀结束
                throw new SecKillCloseException("seckill is closed!");
            }else {
//           记录购买行为
                int insertCount =  successKilledDao.insertSuccessKilled(secKillId,userPhone);
//           唯一的secKillId,userPhone
                if (insertCount <= 0 ){
//                重复秒杀
                    throw  new RepeatKillException("seckill repeated");
                }else {
//                秒杀成功
                    SuccessKill successKill = successKilledDao.queryByIdWithSecKill(secKillId,userPhone);
//                    用SecKillStateEnum.SUCCESS，比较友好，可以重复使用
                    return new SecKillExecution(secKillId, SecKillStateEnum.SUCCESS,successKill);
                }
            }
        }
        catch (SecKillCloseException e1){
            throw e1;
        }
        catch (RepeatKillException e2){
            throw e2;
        }
        catch (Exception e){
            logger.error(e.getMessage(),e);
//            所有编译期异常转化为运行期异常
            throw new SecKillException("seckill inner error:" + e.getMessage());
        }
    }
}
